package com.hxm.messenger;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private EditText editText1, editText2;
    private TextView tvSum;
    //服务端Messenger
    private Messenger serviceMessenger;
    private boolean isConn;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isConn = true;
            serviceMessenger = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceMessenger = null;
            isConn = false;
        }
    };

    private Messenger messenger = new Messenger(new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2000) {
                tvSum.setText(String.format(Locale.CHINA, "结果是：%d", msg.arg1));
            }
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText1 = (EditText) findViewById(R.id.edit_one);
        editText2 = (EditText) findViewById(R.id.edit_two);
        tvSum = (TextView) findViewById(R.id.tv_sum);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    public void sum(View view) {
        Intent intent = new Intent();
        intent.setAction("com.hxm.sumserver");
        intent.setPackage(getPackageName());
        bindService(intent, connection, BIND_AUTO_CREATE);
        int arg1 = Integer.parseInt(editText1.getText().toString());
        int arg2 = Integer.parseInt(editText2.getText().toString());
        Message message = Message.obtain(null, 1000, arg1, arg2);
        message.replyTo = messenger;
        try {
            if (isConn) {
                serviceMessenger.send(message);
            } else {
                Toast.makeText(this, "服务未连接", Toast.LENGTH_SHORT).show();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
